"""区域选择窗口：参考 apps/test.py，通过拖动线条划分三个矩形区域"""

from PyQt5.QtCore import Qt, QRect, QPoint
from PyQt5.QtGui import QPainter, QColor, QPen, QBrush
from PyQt5.QtWidgets import QWidget


class DraggableLine:
    """可拖动的单条线（水平或垂直）"""

    def __init__(self, orientation, position, min_pos, max_pos):
        self.orientation = orientation  # 'horizontal' or 'vertical'
        self.position = position
        self.min_pos = min_pos
        self.max_pos = max_pos
        self.is_dragging = False
        self.drag_offset = 0

    def contains_point(self, point, margin=8):
        if self.orientation == 'horizontal':
            return abs(point.y() - self.position) < margin
        else:
            return abs(point.x() - self.position) < margin

    def start_drag(self, point):
        self.is_dragging = True
        if self.orientation == 'horizontal':
            self.drag_offset = point.y() - self.position
        else:
            self.drag_offset = point.x() - self.position

    def drag(self, point):
        if not self.is_dragging:
            return
        if self.orientation == 'horizontal':
            new_pos = point.y() - self.drag_offset
            self.position = max(self.min_pos, min(self.max_pos, new_pos))
        else:
            new_pos = point.x() - self.drag_offset
            self.position = max(self.min_pos, min(self.max_pos, new_pos))

    def stop_drag(self):
        self.is_dragging = False


class LineRegionSelector(QWidget):
    """半透明置顶窗口，通过 4 条水平线 + 2 条竖线划分 3 个矩形区域"""

    def __init__(self, parent_window, initial_coords=None):
        super().__init__()
        self.parent_window = parent_window

        # 使用当前屏幕几何信息
        screen = self.screen() or (self.windowHandle().screen() if self.windowHandle() else None)
        if screen:
            geom = screen.geometry()
            self.screen_width = geom.width()
            self.screen_height = geom.height()
        else:
            self.screen_width = 1920
            self.screen_height = 1080

        # 初始线条位置（用户指定的默认坐标，或由外部传入的坐标）
        top_margin = 0
        bottom_margin = self.screen_height
        left_margin = 0
        right_margin = self.screen_width

        # 默认坐标（在没有传入坐标或输入框为空时使用）
        default_y1, default_y2, default_y3, default_y4 = 310, 345, 465, 755
        default_x1, default_x2 = 1120, 1560

        # 从 initial_coords 中取值（如果由外部传入且有效）
        if initial_coords is not None:
            y1 = initial_coords.get('y1', default_y1) or default_y1
            y3 = initial_coords.get('y3', default_y2) or default_y2
            y5 = initial_coords.get('y5', default_y3) or default_y3
            y6 = initial_coords.get('y6', default_y4) or default_y4
            x1 = initial_coords.get('x1', default_x1) or default_x1
            x2 = initial_coords.get('x2', default_x2) or default_x2
        else:
            y1, y3, y5, y6 = default_y1, default_y2, default_y3, default_y4
            x1, x2 = default_x1, default_x2

        # 水平线默认 y：y1, y3, y5, y6（或默认值）
        self.h_lines = [
            DraggableLine('horizontal', int(y1), top_margin, bottom_margin),
            DraggableLine('horizontal', int(y3), top_margin, bottom_margin),
            DraggableLine('horizontal', int(y5), top_margin, bottom_margin),
            DraggableLine('horizontal', int(y6), top_margin, bottom_margin),
        ]

        # 垂直线默认 x：x1, x2（或默认值）
        self.v_lines = [
            DraggableLine('vertical', int(x1), left_margin, right_margin),
            DraggableLine('vertical', int(x2), left_margin, right_margin),
        ]

        self.current_drag_line = None
        self.setMouseTracking(True)

        # 半透明置顶窗口
        self.setWindowFlags(
            Qt.FramelessWindowHint
            | Qt.WindowStaysOnTopHint
        )
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.showFullScreen()
        self.raise_()
        self.activateWindow()

    # -------- 绘制 --------
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 整体半透明蒙版
        painter.setBrush(QBrush(QColor(0, 0, 0, 120)))
        painter.setPen(Qt.NoPen)
        painter.drawRect(self.rect())

        # 计算三个区域
        regions = self._calculate_regions()

        # 被选中的三个区域：降低蒙版透明度（更亮一点）
        painter.setBrush(QBrush(QColor(0, 0, 0, 60)))
        painter.setPen(Qt.NoPen)
        for rect in regions:
            painter.drawRect(rect)

        # 绘制线条（细线）
        # 水平线：红色
        pen_h = QPen(QColor(255, 0, 0), 1)
        painter.setPen(pen_h)
        for line in self.h_lines:
            y = int(line.position)
            painter.drawLine(0, y, self.screen_width, y)

        # 垂直线：红色
        pen_v = QPen(QColor(255, 0, 0), 1)
        painter.setPen(pen_v)
        for line in self.v_lines:
            x = int(line.position)
            painter.drawLine(x, 0, x, self.screen_height)

        # 左上角提示文字（红色）
        painter.setPen(QColor(255, 0, 0))
        painter.drawText(20, 30, "左键拖动线条，右键确认并退出")

    def _calculate_regions(self):
        """计算三个矩形区域（与 test.py 保持一致，只是扩展到整屏坐标）"""
        h_positions = sorted([line.position for line in self.h_lines])
        v_positions = sorted([line.position for line in self.v_lines])

        h1, h2, h3, h4 = h_positions
        v1, v2 = v_positions

        regions = []
        # 信息区域（上）：水平在 h1~h2，垂直 v1~v2
        regions.append(QRect(int(v1), int(h1), int(v2 - v1), int(h2 - h1)))
        # 题目区域（中）：h2~h3
        regions.append(QRect(int(v1), int(h2), int(v2 - v1), int(h3 - h2)))
        # 选项区域（下）：h3~h4
        regions.append(QRect(int(v1), int(h3), int(v2 - v1), int(h4 - h3)))

        return regions

    def _apply_coordinates_and_close(self):
        """将三个区域坐标写回到父窗口输入框，并关闭自身"""
        if not self.parent_window:
            self.close()
            return

        regions = self._calculate_regions()

        # 信息区域 -> x1,y1,x2,y2
        info = regions[0]
        self.parent_window.input_x1.setText(str(info.left()))
        self.parent_window.input_y1.setText(str(info.top()))
        self.parent_window.input_x2.setText(str(info.right()))
        self.parent_window.input_y2.setText(str(info.bottom()))

        # 题目区域 -> x3,y3,x4,y4
        question = regions[1]
        self.parent_window.input_x3.setText(str(question.left()))
        self.parent_window.input_y3.setText(str(question.top()))
        self.parent_window.input_x4.setText(str(question.right()))
        self.parent_window.input_y4.setText(str(question.bottom()))

        # 选项区域 -> x5,y5,x6,y6
        option = regions[2]
        self.parent_window.input_x5.setText(str(option.left()))
        self.parent_window.input_y5.setText(str(option.top()))
        self.parent_window.input_x6.setText(str(option.right()))
        self.parent_window.input_y6.setText(str(option.bottom()))

        self.close()

    # -------- 鼠标事件 --------
    def mousePressEvent(self, event):
        if event.button() == Qt.RightButton:
            # 右键确认并关闭
            self._apply_coordinates_and_close()
            return

        if event.button() != Qt.LeftButton:
            return

        pos = event.pos()
        # 先检查水平线
        for line in self.h_lines:
            if line.contains_point(pos):
                self.current_drag_line = line
                line.start_drag(pos)
                return
        # 再检查垂直线
        for line in self.v_lines:
            if line.contains_point(pos):
                self.current_drag_line = line
                line.start_drag(pos)
                return

    def mouseMoveEvent(self, event):
        if self.current_drag_line and self.current_drag_line.is_dragging:
            self.current_drag_line.drag(event.pos())
            self.update()

    def mouseReleaseEvent(self, event):
        if self.current_drag_line:
            self.current_drag_line.stop_drag()
            self.current_drag_line = None


class RegionSelectorDialog(QWidget):
    """点击"选择区域"时创建半透明划线窗口，关闭时坐标自动回写"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent_window = parent

        # 从父窗口输入框读取现有坐标，用于初始化线条位置
        initial_coords = {}

        if self.parent_window is not None:
            def get_int(text):
                text = text.strip()
                if not text:
                    return None
                try:
                    return int(text)
                except ValueError:
                    return None

            x1 = get_int(self.parent_window.input_x1.text())
            y1 = get_int(self.parent_window.input_y1.text())
            x2 = get_int(self.parent_window.input_x2.text())
            y2 = get_int(self.parent_window.input_y2.text())
            x3 = get_int(self.parent_window.input_x3.text())
            y3 = get_int(self.parent_window.input_y3.text())
            x4 = get_int(self.parent_window.input_x4.text())
            y4 = get_int(self.parent_window.input_y4.text())
            x5 = get_int(self.parent_window.input_x5.text())
            y5 = get_int(self.parent_window.input_y5.text())
            x6 = get_int(self.parent_window.input_x6.text())
            y6 = get_int(self.parent_window.input_y6.text())

            # 按你的规则：水平线用 y1, y3, y5, y6；竖线用 x1, x2
            if y1 is not None:
                initial_coords['y1'] = y1
            if y3 is not None:
                initial_coords['y3'] = y3
            if y5 is not None:
                initial_coords['y5'] = y5
            if y6 is not None:
                initial_coords['y6'] = y6
            if x1 is not None:
                initial_coords['x1'] = x1
            if x2 is not None:
                initial_coords['x2'] = x2

        # 创建划线选择器（如 initial_coords 为空，将在内部使用默认坐标）
        self.selector = LineRegionSelector(self.parent_window, initial_coords if initial_coords else None)
        self.close()

